import React, { useEffect, useRef } from 'react'
import {
  Card, Breadcrumb, Form, Radio, DatePicker, Button, Table, Image,
  Tag, Space, Popconfirm, message
} from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import styles from './index.module.scss'
import { Link, useHistory } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { getArticleList, delArticle } from '@/store/actions/article'
import errorImg from '@/assets/error.png'
import Channel from '@/components/Channel'

export default function Article() {
  const dispatch = useDispatch()
  const articles = useSelector(state => state.article.articles)
  const params = useRef({})
  const history = useHistory()

  useEffect(() => {
    // 获取文章数据
    dispatch(getArticleList())
  }, [dispatch])

  // 筛选-表单提交
  const onFinish = (values) => {
    if (values.status !== -1) {
      params.current.status = values.status
    }

    params.current.channel_id = values.channel_id
    if (values.date) {
      params.current.begin_pubdate = values.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
      params.current.end_pubdate = values.date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
    }
    // 从第一页开始筛选
    params.current.page = 1
    dispatch(getArticleList(params.current))
  }

  // 删除
  const del = async (id) => {
    await dispatch(delArticle(id))
    // 获取文章数据
    await dispatch(getArticleList(params.current))
    message.success('删除成功')
  }
  // 状态数据
  const STATUS = [
    { id: -1, title: '全部', color: 'magenta' },
    { id: 0, title: '草稿', color: 'gold' },
    { id: 1, title: '待审核', color: 'volcano' },
    { id: 2, title: '审核通过', color: 'green' },
    { id: 3, title: '审核失败', color: 'red' }
  ]

  // 表格列
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render(cover) {
        if (cover.type === 0) {
          return <Image
            width={90}
            height={50}
            src={errorImg}
          />
        } else {
          return <Image
            width={90}
            height={50}
            src={cover.images[0]}
            fallback={errorImg}
          />
        }
      }
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status) {
        const obj = STATUS.find(item => item.id === status)
        return <Tag color={obj.color}>{obj.title}</Tag>
      }
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      dataIndex: 'id',
      render(id) {
        return (
          <Space>
            <Button type="primary" shape="circle" icon={<EditOutlined />}
              onClick={() => history.push(`/home/publish/${id}`)}></Button>
            <Popconfirm title="确定要删除该文章吗？" onConfirm={() => del(id)}>
              <Button type="danger" shape="circle" icon={<DeleteOutlined />} />
            </Popconfirm>
          </Space>
        )
      }
    },
  ];
  return (
    <div className={styles.root}>
      <Card title={
        <Breadcrumb>
          <Breadcrumb.Item>
            <Link to="/home">首页</Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>内容管理</Breadcrumb.Item>
        </Breadcrumb>
      } >
        <Form
          layout="horizontal"
          initialValues={{ status: -1 }}
          onFinish={onFinish}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              {
                STATUS.map(item => (
                  <Radio value={item.id} key={item.id}>{item.title}</Radio>
                ))
              }
            </Radio.Group>
          </Form.Item>
          <Form.Item label="频道" name="channel_id">
            <Channel></Channel>
          </Form.Item>
          <Form.Item label="日期" name="date">
            <DatePicker.RangePicker ></DatePicker.RangePicker>
          </Form.Item>
          <Form.Item >
            <Button type="primary" htmlType="submit">筛选</Button>
          </Form.Item>
        </Form>
      </Card>
      <Card title={`根据筛选条件共查询到${articles.total_count}条结果:`} style={{ marginTop: 10 }}>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={articles.results}
          pagination={{
            position: ['bottomCenter'],
            total: articles.total_count,
            pageSize: articles.per_page,
            current: articles.page,
            onChange(page, pageSize) {
              params.current.page = page
              params.current.per_page = pageSize
              dispatch(getArticleList(params.current))
            }
          }}
        />;
          {/* rowKey={(record) => record.id}  */}
      </Card>
    </div>
  )
}
